//
//  WYAddToCartAnimation.m
//  LoveFreshBee
//
//  Created by admin on 16/4/8.
//  Copyright © 2016年 wyzc. All rights reserved.
//

#import "WYAddToCartAnimation.h"
#import "WYRedDotView.h"

@interface WYAddToCartAnimation ()
@property(nonatomic,weak) CALayer *layer;
@end


@implementation WYAddToCartAnimation
-(void)addToCartAnimationWithImageView:(UIImageView *)imageView
{
    CALayer *layer=[CALayer layer];
    self.layer=layer;
    layer.anchorPoint=CGPointZero;
    UIWindow *keyWindow=[UIApplication sharedApplication].keyWindow;
     [keyWindow.layer addSublayer:layer];
   
    CGRect imgFrame=[imageView convertRect:imageView.bounds toView:keyWindow];
    layer.frame=imgFrame;
    layer.contents=imageView.layer.contents;
     CGPoint endPoint=CGPointMake(SCREEN_WIDTH*0.6, SCREEN_HEIGHT-49);
//    CABasicAnimation *positionAnimation=[CABasicAnimation animationWithKeyPath:@"position"];
//   positionAnimation.toValue=[NSValue valueWithCGPoint:point];
//
//    positionAnimation.duration=0.8;
//    [layer addAnimation:positionAnimation forKey:nil];
    
    CAKeyframeAnimation *pathAnimation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path=CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, imgFrame.origin.x, imgFrame.origin.y);
    CGPathAddCurveToPoint(path, NULL, imgFrame.origin.x, imgFrame.origin.y, (endPoint.x-imgFrame.origin.x)*0.5, (endPoint.y-imgFrame.origin.y)*0.5, endPoint.x, endPoint.y);
    pathAnimation.path=path;
    //pathAnimation.duration=0.8;
   // [layer addAnimation:pathAnimation forKey:nil];
    
    CABasicAnimation *transformAnimation=[CABasicAnimation animationWithKeyPath:@"transform"];
    CATransform3D transform=CATransform3DMakeScale(0.3, 0.3, 1);
    transformAnimation.toValue=[NSValue valueWithCATransform3D:transform];

    CABasicAnimation *opacityAnimation=[CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.toValue=@(0.7);
    
    CAAnimationGroup *animGroup=[CAAnimationGroup animation];
    animGroup.animations=@[pathAnimation,transformAnimation,opacityAnimation];
    animGroup.delegate=self;
    animGroup.duration=0.8;
    [layer addAnimation:animGroup forKey:@"group"];
  
    WYRedDotView *redView=[WYRedDotView sharedInstance];
    [redView addToCart];
 }

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    [self.layer removeAnimationForKey:@"group"];
    [self.layer removeFromSuperlayer];
    //开启事务
    [CATransaction begin];
    //禁用隐式动画
    [CATransaction setDisableActions:YES];
    
    _layer.position=[[anim valueForKey:@"group"] CGPointValue];
    
    //提交事务
    [CATransaction commit];
}

@end








